package com.jair.crawler.mijia;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import net.sf.json.JSONObject;

/**
 * This example demonstrates basics of request execution with the HttpClient fluent API.
 */
public class postTest {

    public static void main(String[] args)throws Exception {
    	Map<String,String> paramMaps = new HashMap<String,String>();
    	//1.通过抓包获得sign
    	//paramMaps.put("sign", "0a129dcec5208daee741221ec0113c6e");之前获取的
    	paramMaps.put("sign", "b47a1ccd8c1cef32e279c07a2143e59d");
    	//2.获取sessionId和productId
    	paramMaps.putAll(getSaleParam(paramMaps.get("sign")));
    	//2.通过session获取验证码和captchaVerify,只能执行一次
    	//getCaptcha(paramMaps.get("sessionId"));
    	
    	paramMaps.put("captchaVerify","590c18f4e0c8017f130000058c1dbaae");
    	paramMaps.put("captcha", "手日老间");
    	
    	//4.通过captcha获取
    	//getToken(paramMaps.get("captcha"),paramMaps.get("captchaVerify"));
    	//5.获取的token
    	paramMaps.put("token", "590c18f4e0c8017f130000058c1dbaae");
    	submit(paramMaps);
    	
    	System.out.println(paramMaps);
    	//返回的结果：预约前 result={"code":10001,"msg":"现在没有可以预约购买的商品"}
    }
    
    /**
     * 获取sessionId和productId
     * @throws Exception
     */
    public static Map<String,String> getSaleParam(String sign) throws Exception{
    	Map<String,String> map = new HashMap<String,String>();
    	Response response = Request.Get("http://act.men.mi.com/reservation/sale")
    			//.viaProxy(new HttpHost("127.0.0.1", 8888))
    			.addHeader("Cookie", "sign="+sign)
    			.execute();
    	String str = response.returnContent().asString();
    	Document doc = Jsoup.parse(str);
    	String sessionId = getSessionId(doc);
    	List<String> productIdList = getProductIdList(doc);
    	System.out.println("productIdList="+productIdList);
    	System.out.println("sessionId="+sessionId);
    	if(productIdList!= null && productIdList.size()>0){
    		map.put("productId", productIdList.get(0));
    	}
    	map.put("sessionId", sessionId);
    	return map;
    }
    
    //��Ӧ���� isClosed=false ����ԤԼ
    public static void checkSign(String sign) throws Exception{
    	Response response = Request.Get("http://act.men.mi.com/reservation/check/sign/7c9bc1c2983e48e39eef2e8d18ca6633")
    	    	.viaProxy(new HttpHost("127.0.0.1", 8888))
    	        .addHeader("Cookie", "sign="+sign)
    	      	.execute();
    	        System.out.println(response.returnContent().asString());
    }
    
    /**
     * ͨ��Document��ȡsessionId
     * @throws Exception
     */
    public static String  getSessionId(Document doc) throws Exception{
		Elements productUl = doc.getElementsByTag("script");
		for(int i=0;i<productUl.size();i++){
			String data = productUl.get(i).data();
			if(data.indexOf("_page_data") > -1){
				String regEx = "(?<=sId     : \\')(.+?)(?=\\')";
			    Pattern pattern = Pattern.compile(regEx);
			    Matcher m = pattern.matcher(data);
			    m.find();
			    return m.group();
			}
		}
		return null;
    }
    /**
     * ͨ��Document��ȡ��Ʒ�б�
     * @param doc
     * @return
     * @throws Exception
     */
    public static List<String> getProductIdList(Document doc) throws Exception{
    		Element productUl = doc.getElementById("J_productIdInput");
    		if(productUl == null){
    			return null;
    		}
    		Elements productLiList = productUl.getElementsByTag("li");
    		List<String> productIdList = new ArrayList<String>();
    		if(productLiList.size() > 0){
    			for(int i=0 ;i < productLiList.size();i++){
    				//Element liElement = productLiList.get(i);
    				//Elements elements = liElement.getElementsByClass("txt");
    				//String productId = null;
    				//String productName = null;
    				if(productLiList.get(i).hasAttr("data-id")){
    					productIdList.add(productLiList.get(i).attr("data-id"));
    				}
//    				if(elements != null && elements.size() > 0){
//    					productName = elements.get(0).childNode(0).toString();
//    				}
//    				if(productId != null && productName != null){
//    					productMap.put(productId, productName);
//    				}
    			}
    		}
    		return productIdList;
    }
    
    /**
     * ��ȡcaptchaVerify
     * @param sessionId
     * @return
     * @throws Exception
     */
    public static String getCaptcha(String sessionId) throws Exception{
    	String fileName = "D://1.jpeg";
    	Response response = Request.Get("http://captcha.hd.mi.com/captcha?style=chinese&service=act.men.mi.com&sessionId="+sessionId)
    	        .addHeader("Cookie", "sessionId="+sessionId)
    	      	.execute();
    	//��֤��ͼƬ
    	HttpResponse httpResponse = response.returnResponse();
    	Header captchaVerifyHeader = httpResponse.getFirstHeader("Set-Cookie");
    	HttpEntity entity = httpResponse.getEntity();
    	InputStream ins = entity.getContent();
    	File file = new File(fileName);
    	inputstreamtofile(ins,file);//д�ļ�
    	if(captchaVerifyHeader == null){
    		return null;
    	}
    	HeaderElement[] HeaderElements = captchaVerifyHeader.getElements();
    	for(int i=0;i<HeaderElements.length;i++){
    		if("captchaVerify".equals(HeaderElements[i].getName())){
    			System.out.println("captchaVerify="+HeaderElements[i].getValue());
    			return HeaderElements[i].getValue();
    		}
    	}
		return null;
    }
    /**
     * ͨ����֤���captchaVerify ��ȡtoken
     * @param answer
     * @param captchaVerify
     * @return
     * @throws Exception
     */
    public static String getToken(String answer,String captchaVerify) throws Exception{
    	Response response = Request.Get("http://captcha.hd.mi.com/captcha/auth?answer="+answer+"&service=act.men.mi.com&callback=jsonpCaptcha&jsonpcallback=jsonpCaptcha")
    	        .addHeader("Cookie", "captchaVerify="+captchaVerify)
    	      	.execute();
    	String str = response.returnContent().asString();
    	String regEx = "(?<=jsonpCaptcha\\()(.+?)(?=\\))";
	    Pattern pattern = Pattern.compile(regEx);
	    Matcher m = pattern.matcher(str);
	    m.find();
	   String jsonStr = m.group();
	   JSONObject object = JSONObject.fromObject(jsonStr);
	   JSONObject meta = object.getJSONObject("meta");
	   if("200".equals(meta.optString("status"))){
		   JSONObject data = object.getJSONObject("data");
		   String token = data.optString("token");
		   System.out.println("token="+token);
		   return token;
	   }
	   System.out.println(jsonStr);
    	return null;
    }
    
    public static void submit(Map<String,String> map) throws Exception{
    	if(!map.containsKey("sign") || "".equals(map.get("sign"))){
    		System.out.println("没有sign");
    		return;
    	}
    	if(!map.containsKey("captchaVerify") || "".equals(map.get("captchaVerify"))){
    		System.out.println("没有captchaVerify");
    		return;
    	}
    	if(!map.containsKey("captcha") || "".equals(map.get("captcha"))){
    		System.out.println("没有captcha");
    		return;
    	}
    	if(!map.containsKey("token") || "".equals(map.get("token"))){
    		System.out.println("没有token");
    		return;
    	}
    	Response response = Request.Post("http://act.men.mi.com/reservation/submit/sign/"+map.get("sign"))
    			.addHeader("Cookie", "sign="+map.get("sign")+";captchaVerify="+map.get("captchaVerify"))
		       .bodyForm(Form.form()
		    		   .add("city", "36")
		    		   .add("mihome", "MI0104")
		    		   .add("productId", "2be3nojq")
		    		   .add("day", "20170506")
		    		   .add("time", "1012")
		    		   .add("username", "温杰")
		    		   .add("idCard", "142431199110267532")
		    		   .add("phoneNo", "18519661642")
		    		   .add("reservationId", "66")//变化
		    		   .add("captcha", map.get("captcha"))
		    		   .add("token", map.get("token"))
		    		   .build())
		       .execute();
    	String responseStr = response.returnContent().asString();
    	System.out.println("result="+responseStr);
    }
    
    public static void inputstreamtofile(InputStream ins,File file) throws IOException{
    	OutputStream os = new FileOutputStream(file);
    	int bytesRead = 0;
    	byte[] buffer = new byte[8192];
    	while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
    	os.write(buffer, 0, bytesRead);
    	}
    	os.close();
    	ins.close();
    	}
}
